package ge.telasi.tasks.ui.search;

import ge.telasi.tasks.search.Condition;
import ge.telasi.tasks.ui.UIUtils;
import javax.swing.Icon;

/**
 * Text search field.
 * 
 * @author dimitri
 */
public class TextField extends Field {
    public static final int EXACT = 0;
    public static final int START = 1;
    public static final int END = 2;
    public static final int CONTAINS = 3;

    private int method = EXACT;
    private String text;

    public TextField(String name, String humanName) {
        super(name, humanName);
    }

    public int getMethod() {
        return method;
    }

    public void setMethod(int method) {
        this.method = method;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    @Override
    public String getType() {
        return "text";
    }

    @Override
    public Icon getIcon() {
        return UIUtils.getIcon16x16("text_lowercase.png");
    }

    @Override
    public Condition getCondition() {
        if (text == null || text.trim().length() == 0) {
            return null;
        }
        String fieldName = getNextField();

        // create where condition
        StringBuilder b = new StringBuilder();
        b.append(" ( ");
        b.append(getSysName());
        if (method == EXACT) {
            b.append(" = ");
        } else {
            b.append(" LIKE ");
        }
        b.append(":");
        b.append(fieldName);
        b.append(" ) ");
        String where = b.toString();

        // create substitude value
        String fieldValue = text;
        if (method == START) {
            fieldValue = fieldValue + "%";
        } else if (method == END) {
            fieldValue = "%" + fieldValue;
        } else if (method == CONTAINS) {
            fieldValue = "%" + fieldValue + "%";
        }
        
        // build condition
        Condition condition = new Condition();
        condition.setCondition(where);
        condition.getSubstitutions().put(fieldName, fieldValue);
        return condition;
    }

}
